<%--
  Created by IntelliJ IDEA.
  User: CM
  Date: 2017/4/1
  Time: 12:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>商品类别管理</title>
    <jsp:include page="../../common/header.jsp"></jsp:include>
    <jsp:include page="../../common/cloud-head.jsp"></jsp:include>
    <style>
        .dd3-content .active {
            box-shadow: 0 0 5px #2bff02;
        }

        .dd-item i.fa.fa-close {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            z-index: 999;
            width: 1rem;
            height: 1rem;
            background: #f00;
            border-radius: 50%;
            box-shadow: 0 0 10px #666 inset;
            cursor: pointer;
        }

        li.dd-item {
            position: relative;
        }

        .dd-handle.dd3-handle {
            display: none;
        }

        .hide-price-tip {
            color: #f00 !important;
            margin: 0 .8rem !important;
        }
    </style>
</head>
<body>

<div class="page-content">
    <div class="row">
        <div class="col-md-4">
            <div class="card">
                <div class="card-action">
                    商品类别列表
                    <button class="btn" style="float: right" onclick="save()">保存</button>
                    <div style="clear: both"></div>
                </div>
                <div class="card-content">
                    <div id="nestable" style="max-height: 38rem;overflow-y: auto;">
                        <ol class="dd-list" id="mainList">

                        </ol>
                    </div>
                    <div style="clear: both;">

                    </div>
                    <div class="row" style="display:none;">
                        <p>JSON结果</p>
                        <textarea class="form-control" id="nestable-output"><pre></pre></textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-8">
            <div class="card">
                <div class="card-action">
                    操作
                </div>
                <div class="card-content">
                    <div class="form-group">
                        <label>当前类别</label>
                        <div class="clear"></div>
                        <div class="col-md-12 show-box">
                            <label id="currentClass" style="color: darkred;" data-id=""></label>
                            <i class="fa fa-edit" id="modifyCurrent" style="cursor: pointer;color:orangered">编辑</i>
                        </div>

                        <div class="col-md-12 modify-box" style="display: none">
                            <input class="col-md-4" style="display: inline-block;width:33.3333% !important;" type="text"
                                   value="" id="currentClassModify" placeholder="请输入修改后的名称"/>
                            <div class="switch col-md-4">
                                <label>
                                    <input id="invailed_price" type="checkbox">
                                    <span class="lever"></span>
                                    隐藏价格
                                </label>
                            </div>

                            <button class="btn" id="saveCurrentModifyBtn">确定</button>
                        </div>
                        <div class="clear"></div>
                    </div>
                    <div class="card-action"><i class="fa fa-plus"></i>添加子类</div>
                    <div class="form-group" style="width: 90%;margin: 0 auto;">
                        <div class="col-md-6">
                            <label>子类名称</label>
                            <input type="text" value="" id="subClassName"
                                   style="display: inline-block;width:auto;min-width:20rem;" placeholder="请输入子类名称">
                        </div>
                        <div class="switch col-md-4">
                            <label>
                                <input id="sub_invailed_price" type="checkbox">
                                <span class="lever"></span>
                                隐藏价格
                            </label>
                        </div>
                        <button class="btn" id="subClassAddBtn" style="float: right">添加</button>
                        <div style="clear: both;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="listTmpl">
    <li class="dd-item dd3-item" data-id="\${_id}">
        <div class="dd-handle dd3-handle"></div>
        <div class="dd3-content">
            <span class="title">\${title}</span>
            {{if hidePrice}}
            {{if hidePrice == true}}
            <span class="hide-price-tip">(隐藏价格)</span>
            {{/if}}
            {{/if}}
        </div>
        <i class="fa fa-close"></i>
        <ol class="dd-list">
        </ol>
    </li>
</script>

<script type="text/html" id="childTmpl">
    {{if isEmpty(children) == false}}
    {{each(i,cd) children}}
    {{if cd.hidePrice}}
    <li class="dd-item dd3-item" data-id="\${cd._id}" is-hide-price="\${hidePrice}">
        {{else}}
    <li class="dd-item dd3-item" data-id="\${cd._id}" is-hide-price="false">
        {{/if}}
        <div class="dd3-content">
            <span class="title">\${cd.title}</span>
            {{if cd.hidePrice == true}}
            <span class="hide-price-tip">(隐藏价格)</span>
            {{/if}}
        </div>
        <i class="fa fa-close"></i>
    </li>
    {{/each}}
    {{/if}}
</script>

<script type="text/html" id="itemTmpl">
    {{if hidePrice}}
    <li class="dd-item dd3-item" data-id="\${_id}" is-hide-price="\${hidePrice}">
        {{else}}
    <li class="dd-item dd3-item" data-id="\${_id}" is-hide-price="false">
        {{/if}}
        <div class="dd3-content">
            <span class="title">\${title}</span>
            {{if hidePrice}}
            {{if hidePrice == true}}
            <span class="hide-price-tip">(隐藏价格)</span>
            {{/if}}
            {{/if}}
        </div>
        <i class="fa fa-close"></i>
        {{if isEmpty(children) == true }}
        <ol class="dd-list">
            {{each(i,cd) children}}
            {{if cd.hidePrice}}
            <li class="dd-item dd3-item" data-id="\${cd._id}" is-hide-price="\${hidePrice}">
                {{else}}
            <li class="dd-item dd3-item" data-id="\${cd._id}" is-hide-price="false">
                {{/if}}
                <div class="dd3-content"><span class="title">\${cd.title}</span>
                    {{if cd.hidePrice}}
                    {{if cd.hidePrice == true}}
                    <span class="hide-price-tip">(隐藏价格)</span>
                    {{/if}}
                    {{/if}}
                </div>
                <i class="fa fa-close"></i>
            </li>
            {{/each}}
        </ol>
        {{/if}}
    </li>
</script>

<script>
    $(function () {
        $("#modifyCurrent").unbind().bind("click", function () {
            $(".show-box").hide("slow", function () {
                $(".modify-box").show("slow");
            });
        })
        $("#saveCurrentModifyBtn").unbind().bind("click", function () {

            var id = $("#currentClass").attr("data-id");
            var hidePrice = $("#invailed_price")[0].checked;
            if (isEmpty(id)) {
                Messenger().run({
                    "successMessage": "请选择要修改的类别",
                    action: function (opts) {
                        return opts.success();
                    }
                })

                return -1;
            }

            var val = $("#currentClassModify").val();

            if (isEmpty(val)) {
                Messenger().run({
                    "successMessage": "类别名称不能为空",
                    action: function (opts) {
                        return opts.success();
                    }
                })

                return -1;
            }

            $(".dd-list li[data-id=\"" + id + "\"]>.dd3-content").html("<span class=\"title\">" + val + "</span>" + (hidePrice ? "<span class=\"hide-price-tip\">(隐藏价格)</span>" : ""));
            $(".dd-list li[data-id=\"" + id + "\"]>.dd3-content").click();
            $(".dd-list li[data-id=\"" + id + "\"]").attr("is-hide-price", hidePrice);
            $("#currentClassModify").val("");
            $("#nestable-output").val(JSON.stringify(getTypeData()));
        })


        $("#subClassAddBtn").click(function () {
            var val = $("#subClassName").val();
            var parentid = $("#currentClass").attr("data-id");
            if (isEmpty(parentid)) {
                $.msgError("请选择要添加子类的大类");
                return -1;
            }
            var maxId = 0;
            if ($("li[data-id=\"" + parentid + "\"]").find("li").length > 0) {
                $("li[data-id=\"" + parentid + "\"]").find("li").each(function (idx, childEl) {
                    var childId = $(childEl).attr("data-id");
                    if (parseInt(childId) - maxId > 0) {
                        maxId = parseInt(childId);
                    }
                })
            } else {
                maxId = parseInt(parentid + "0" + maxId);
            }
            var id = (maxId + 1);

            var hidePrice = $("#sub_invailed_price")[0].checked;
            var data = {
                title: val,
                _id: id,
                children: [],
                hidePrice: hidePrice
            }
            var obj = $("#itemTmpl").tmpl(data);

            //console.log("data:%o,obj:%o", data, obj);


            if ($(".dd-item[data-id=\"" + parentid + "\"]>.dd-list").length <= 0) {
                $(".dd-item[data-id=\"" + parentid + "\"]").append('<ol class="dd-list"></ol>')
            }
            $(".dd-item[data-id=\"" + parentid + "\"]>.dd-list").append(obj)
            //console.log("new :%o,item:%o", obj, $(".dd-item[data-id=\"" + parentid + "\"]>ol.dd-list"));


            $("#nestable-output").val(JSON.stringify(getTypeData()));
            $("#subClassName").val("");
            $("#subClassName").focus();


            $("li .fa-close").unbind().bind("click", function () {
                var _this = $(this);
                bootbox.confirm({
                    message: "确定删除此分类?这将会删除该分类下的所有子类别",
                    callback: function (res) {
                        if (res == true) {
                            // check good info
                            _this.parent().remove();
                            $("#nestable-output").val(JSON.stringify(getTypeData()));
                            bootbox.alert("删除成功");
                        } else {
                            bootbox.alert("取消成功");
                        }
                    }
                })

            })

        })

        loadList();
    })


    function loadList() {
        asyncAjax({
            url: "${ctx}/shop/good/type/data",
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == 0) {
                    Messenger().run({
                        successMessage: '请求数据成功',
                        showCloseButton: true,
                        action: function (opts) {
                            return opts.success();
                        }
                    });
                    if (isEmpty(res.data)) {
                        Messenger().run({
                            successMessage: '您尚未配置过上配类别，默认显示示例类别！',
                            showCloseButton: true,
                            action: function (opts) {
                                return opts.success();
                            }
                        });
                        var eg = [{
                            "_id": "0",
                            "title": "全部",
                            "children": [{"_id": "1", "title": "类别1", "children": []}, {
                                "_id": "2",
                                "title": "类别2",
                                "children": []
                            }, {"_id": "3", "title": "类别3", "children": [{"_id": "4", "title": "二级分类"}]}, {
                                "_id": "5",
                                "title": "二级分类1",
                                "children": []
                            }]
                        }];
                        getList(eg);
                    } else {
                        getList([res.data.list]);
                    }

                    getTypeData()

                    $(".dd3-content").bind("click", function () {

                        $(".modify-box").hide("slow", function () {
                            $(".show-box").show("slow");
                        });
                        $(".dd3-content.active").removeClass("active");
                        $(this).toggleClass("active");

                        $("#currentClass").attr("data-id", $(this).parents("li").attr("data-id"));
                        $("#currentClass").text($(this).find(".title").text());
                        $("#currentClassModify").val($(this).find(".title").text());

                    })


//                    $(".dd3-content:eq(0)").unbind("click");
                    $(".dd3-content:eq(1)").click();

                } else {
                    Messenger().run({
                        errorMessage: '请求数据发生错误:' + res.msg,
                        showCloseButton: true,
                        action: function (opts) {
                            return opts.error();
                        }
                    });
                }


                $("li .fa-close").unbind().bind("click", function () {
                    var _this = $(this);
                    bootbox.confirm({
                        message: "确定删除此分类?这将会删除该分类下的所有子类别",
                        callback: function (res) {
                            if (res == true) {
                                _this.parent().remove();
                                $("#nestable-output").val(JSON.stringify(getTypeData()));
                                bootbox.alert("删除成功");
                            } else {
                                bootbox.alert("取消成功");
                            }
                        }
                    })

                })

            }
        })
    }

    var id = 0;
    function getList(list, _id) {
        if (isEmpty(_id)) {
            getItem(list);
        } else {
            getItem(list, _id);
        }
        $.each(list, function (idx, item) {
            if (!isEmpty(item.children)) {
                getList(item.children, item._id);
            }
        })

    }

    function getItem(item, _id) {
        if (isEmpty(_id)) {
            $("#listTmpl").tmpl(item).appendTo($(".dd-list"));
        } else {
            $("#listTmpl").tmpl(item).appendTo($(".dd-item[data-id=\"" + _id + "\"]>.dd-list"));
        }
    }

    function getTypeData() {
        var data = [];
        $("#mainList>li").each(function (idx, el) {
            var title = $(this).children(".dd3-content").find(".title").text();
            var id = $(this).attr("data-id");
            var _this = $(this);
            var hidePrice = $(this).attr("is-hide-price") == "true" ? true : false;
            var item = {
                id: id, title: title, children: getChildData(_this, idx), hidePrice: hidePrice
            }
            data.push(item);
        })
        return data;
    }

    function getChildData(_this, parentId) {
        var children = [];
        if ($(_this).children(".dd-list")) {

            var child = $(_this).children(".dd-list");

            $(child).children("li").each(function (cidx, childEl) {
                var childTitle = $(this).children(".dd3-content").find(".title").text();
                var childId = $(this).attr("data-id");
                var childEl = $(this);
                var hidePrice = $(this).attr("is-hide-price") == "true" ? true : false;
                children.push({
                    id: childId,
                    title: childTitle,
                    children: getChildData(childEl),
                    hidePrice: hidePrice
                });
            })
        }
        return children;
    }

    function save() {
        var data = getTypeData()[0];
        asyncAjax({
            dataType: "json",
            contentType: "application/json",
            url: "${ctx}/shop/good/type/addOrUpdate",
            data: JSON.stringify(data),
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == 0) {
                    Messenger().run({
                        successMessage: '请求数据成功',
                        showCloseButton: true,
                        action: function (opts) {
                            return opts.success();
                        }
                    });
                } else {
                    Messenger().run({
                        errorMessage: '请求数据发生错误:' + res.msg,
                        showCloseButton: true,
                        action: function (opts) {
                            return opts.error();
                        }
                    });
                }
            }
        })
    }
</script>
</body>
</html>
